package com.abe.jetpack.model.repository

import android.arch.persistence.room.EmptyResultSetException
import com.abe.jetpack.helper.Constant
import com.abe.jetpack.model.entity.http.AuthorEntity
import com.abe.jetpack.model.remote.wanAndroidService
import com.abe.jetpack.model.room.AuthorDao
import io.reactivex.Single
import javax.inject.Inject

class AuthorRepository @Inject constructor(private val service: wanAndroidService, private val dao: AuthorDao) {
    fun loadAuthors(): Single<List<AuthorEntity>> {
        return dao.getAll().onErrorResumeNext {
            if (it is EmptyResultSetException) {
                service.getWeChatAuthor().map { t -> if (t.errorCode == Constant.wanAndroidOK) t.data!! else emptyList() }
            } else {
                throw it
            }
        }
    }

    fun remoteAuthors(): Single<List<AuthorEntity>> {
        return service.getWeChatAuthor().map { t -> if (t.errorCode == Constant.wanAndroidOK) t.data!! else emptyList() }
    }
}